<template>
  <view class="lottery-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">转盘抽奖</text>
      <view class="lottery-info">
        <text class="info-text">剩余次数：</text>
        <text class="count-text">{{ lotteryCount }}</text>
      </view>
    </view>

    <!-- 转盘容器 -->
    <view class="lottery-container">
     <q-turntable ref="lottery" @start="lotteryStart" @success="lotterySuccess"></q-turntable>
    </view>

    <!-- 奖品列表 -->
    <view class="card prize-list-card">
      <view class="list-header">
        <text class="list-title">🎁 奖品列表</text>
      </view>
      <view class="prize-grid">
        <view 
          class="prize-item" 
          v-for="(prize, index) in prizes" 
          :key="index"
        >
          <view class="prize-icon" :style="{ backgroundColor: prize.color }">
            <text class="icon-text">{{ prize.icon }}</text>
          </view>
          <view class="prize-info">
            <text class="prize-title">{{ prize.name }}</text>
            <text class="prize-desc">{{ prize.description }}</text>
          </view>
          <view class="prize-rate">
            <text class="rate-text">{{ prize.probability }}%</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 中奖记录 -->
    <view class="card record-card" v-if="lotteryRecords.length > 0">
      <view class="record-header">
        <text class="record-title">🏆 中奖记录</text>
        <text class="record-count">最近{{ lotteryRecords.length }}次</text>
      </view>
      <view class="record-list">
        <view 
          class="record-item" 
          v-for="(record, index) in lotteryRecords" 
          :key="index"
        >
          <view class="record-time">
            <text class="time-text">{{ formatTime(record.createTime) }}</text>
          </view>
          <view class="record-prize">
            <text class="prize-text">{{ record.prizeName }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 响应式数据
const lotteryCount = ref(0)
const isSpinning = ref(false)
const wheelRotation = ref(0)
const lotteryRecords = ref([])

const data = ref({
	award: 1,
	    awardList: [
	        {
	            title: '特等奖'
	        },
	        {
	            title: '一等奖'
	        },
	        {
	            title: '二等奖'
	        },
	        {
	            title: '三等奖'
	        },
	        {
	            title: '四等奖'
	        },
	        {
	            title: '啥也没有'
	        }
	    ] // 顺时针对应每个奖项
})

const lottery = ref(null)

const lotteryStart = () => {
	let index = 2
	data.value.award = index
	lottery.value.begin(data.value.award)
}

const lotterySuccess = () => {
	const index = data.value.award - 1
	uni.showToast({
		title: `恭喜你获得${data.value.awardList[index].title}`,
		icon: 'none'
	})
}

const prizes = ref([
  {
    id: 1,
    name: '湿粮1袋',
    description: '价值15元湿粮',
    probability: 30,
    color: '#FF6B6B',
    icon: '🥫'
  },
  {
    id: 2,
    name: '湿粮2袋',
    description: '价值30元湿粮',
    probability: 20,
    color: '#4ECDC4',
    icon: '🥫'
  },
  {
    id: 3,
    name: '湿粮5袋',
    description: '价值75元湿粮',
    probability: 10,
    color: '#45B7D1',
    icon: '🥫'
  },
  {
    id: 4,
    name: '谢谢参与',
    description: '下次再来',
    probability: 25,
    color: '#96CEB4',
    icon: '😊'
  },
  {
    id: 5,
    name: '小零食',
    description: '宠物小零食1包',
    probability: 10,
    color: '#FFEAA7',
    icon: '🦴'
  },
  {
    id: 6,
    name: '再来一次',
    description: '获得额外抽奖机会',
    probability: 5,
    color: '#DDA0DD',
    icon: '🎯'
  }
])

// 计算属性
const canSpin = computed(() => {
  return lotteryCount.value > 0 && !isSpinning.value
})

// 加载抽奖数据
const loadLotteryData = async () => {
  try {
    // 这里应该调用后端API获取奖品配置
    // const res = await api.getLotteryConfig()
    // prizes.value = res.data.prizes
    
    loadLotteryCount()
    loadLotteryRecords()
  } catch (error) {
    console.error('加载抽奖数据失败:', error)
  }
}

// 加载抽奖次数
const loadLotteryCount = () => {
  lotteryCount.value = uni.getStorageSync('lotteryCount') || 0
}

// 加载中奖记录
const loadLotteryRecords = () => {
  lotteryRecords.value = uni.getStorageSync('lotteryRecords') || []
}

// 开始抽奖
const startLottery = async () => {
  if (!canSpin.value) return
  
  isSpinning.value = true
  
  try {
    // 调用后端API进行抽奖
    // const res = await api.drawLottery()
    // const winPrize = res.data.prize
    
    // 模拟抽奖
    const winPrize = mockDrawLottery()
    
    // 计算转盘旋转角度
    const prizeIndex = prizes.value.findIndex(p => p.id === winPrize.id)
    const sectorAngle = 360 / prizes.value.length
    const targetAngle = prizeIndex * sectorAngle + sectorAngle / 2
    const spinAngle = 360 * 5 + (360 - targetAngle) // 转5圈后停在目标位置
    
    wheelRotation.value += spinAngle
    
    // 等待动画完成
    setTimeout(() => {
      showPrizeResult(winPrize)
      isSpinning.value = false
      
      // 更新抽奖次数
      lotteryCount.value -= 1
      uni.setStorageSync('lotteryCount', lotteryCount.value)
      
      // 如果中奖是"再来一次"，增加抽奖次数
      if (winPrize.id === 6) {
        lotteryCount.value += 1
        uni.setStorageSync('lotteryCount', lotteryCount.value)
      }
      
      // 保存中奖记录
      saveLotteryRecord(winPrize)
      
    }, 3000)
    
  } catch (error) {
    console.error('抽奖失败:', error)
    isSpinning.value = false
    uni.showToast({
      title: '抽奖失败，请重试',
      icon: 'none'
    })
  }
}

// 模拟抽奖逻辑
const mockDrawLottery = () => {
  const random = Math.random() * 100
  let currentProbability = 0
  
  for (const prize of prizes.value) {
    currentProbability += prize.probability
    if (random <= currentProbability) {
      return prize
    }
  }
  
  // 默认返回谢谢参与
  return prizes.value.find(p => p.id === 4)
}

// 显示中奖结果
const showPrizeResult = (prize) => {
  const title = prize.id === 4 ? '很遗憾' : '恭喜中奖'
  const content = prize.id === 4 ? '谢谢参与，下次再来！' : `恭喜您获得：${prize.name}`
  
  uni.showModal({
    title: title,
    content: content,
    showCancel: false,
    confirmText: '确定'
  })
}

// 保存中奖记录
const saveLotteryRecord = (prize) => {
  const record = {
    prizeName: prize.name,
    prizeId: prize.id,
    createTime: Date.now()
  }
  
  lotteryRecords.value.unshift(record)
  
  // 只保留最近10条记录
  if (lotteryRecords.value.length > 10) {
    lotteryRecords.value = lotteryRecords.value.slice(0, 10)
  }
  
  uni.setStorageSync('lotteryRecords', lotteryRecords.value)
}

// 获取扇形样式
const getSectorStyle = (index) => {
  const sectorAngle = 360 / prizes.value.length
  const startAngle = index * sectorAngle
  
  return {
    transform: `rotate(${startAngle}deg)`,
    backgroundColor: prizes.value[index].color
  }
}

// 获取扇形内容样式
const getSectorContentStyle = (index) => {
  const sectorAngle = 360 / prizes.value.length
  
  return {
    transform: `rotate(${sectorAngle / 2}deg)`
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

// 生命周期钩子
onLoad(() => {
  loadLotteryData()
})

onShow(() => {
  loadLotteryCount()
})
</script>

<style scoped>
.lottery-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
  padding-bottom: 100px;
}

/* 页面标题 */
.page-header {
  padding: 30px 20px 20px;
  text-align: center;
}

.page-title {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #FFB800;
  margin-bottom: 12px;
}

.lottery-info {
  display: flex;
  justify-content: center;
  align-items: center;
}

.info-text {
  font-size: 16px;
  color: #666;
}

.count-text {
  font-size: 20px;
  font-weight: bold;
  color: #FFB800;
  margin-left: 8px;
}

/* 转盘容器 */
.lottery-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.wheel-wrapper {
  position: relative;
  width: 300px;
  height: 300px;
}

.wheel-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
  border: 8px solid #FFB800;
  box-shadow: 0 8px 24px rgba(255, 184, 0, 0.3);
}

.wheel-sector {
  position: absolute;
  width: 50%;
  height: 50%;
  top: 50%;
  left: 50%;
  transform-origin: 0 0;
  clip-path: polygon(0 0, 100% 0, 0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.sector-content {
  position: absolute;
  top: 20%;
  left: 10%;
  transform-origin: 0 0;
  text-align: center;
}

.prize-name {
  font-size: 12px;
  font-weight: bold;
  color: white;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.wheel {
  position: absolute;
  width: 100%;
  height: 100%;
  transition: transform 3s cubic-bezier(0.23, 1, 0.32, 1);
}

.wheel.spinning {
  transition: transform 3s cubic-bezier(0.23, 1, 0.32, 1);
}

.pointer {
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-bottom: 30px solid #FF6B6B;
  z-index: 10;
}

.center-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #FFB800 0%, #FF8F00 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(255, 184, 0, 0.4);
  z-index: 20;
  transition: all 0.3s ease;
}

.center-btn:active {
  transform: translate(-50%, -50%) scale(0.95);
}

.center-btn.disabled {
  background: #ccc;
  box-shadow: none;
}

.btn-text {
  font-size: 14px;
  font-weight: bold;
  color: white;
  text-align: center;
}

/* 奖品列表 */
.prize-list-card {
  margin: 20px 16px;
}

.list-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #FFE082;
}

.list-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.prize-grid {
  
}

.prize-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.prize-item:last-child {
  border-bottom: none;
}

.prize-icon {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.icon-text {
  font-size: 20px;
}

.prize-info {
  flex: 1;
}

.prize-title {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.prize-desc {
  display: block;
  font-size: 12px;
  color: #999;
}

.prize-rate {
  
}

.rate-text {
  font-size: 14px;
  color: #FFB800;
  font-weight: bold;
}

/* 中奖记录 */
.record-card {
  margin: 20px 16px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #FFE082;
}

.record-title {
  font-size: 18px;
  font-weight: bold;
  color: #FFB800;
}

.record-count {
  font-size: 12px;
  color: #999;
}

.record-list {
  
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.record-item:last-child {
  border-bottom: none;
}

.record-time {
  
}

.time-text {
  font-size: 12px;
  color: #999;
}

.record-prize {
  
}

.prize-text {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}
</style>